home *** CD-ROM | disk | FTP | other *** search
/ Sprite 1984 - 1993 / Sprite 1984 - 1993.iso / src / cmds / rdate / port.c < prev    next >
C/C++ Source or Header  |  1993-01-01  |  1KB  |  63 lines

  1. /* port --- routines to deal with sockets and ports for user programs */
  2.  
  3. /* Copyright (c) 1990, W. Keith Pyle, Austin, Texas */
  4.  
  5. #include "rdate.h"
  6.  
  7. /* ------------------------------------------------------------------------- */
  8.  
  9. open_port(host, port)
  10.  
  11. char *host;
  12. int port;
  13.  
  14. {
  15.     int socket_fd;
  16.  
  17.     struct hostent *hentry;
  18.     struct sockaddr_in sa;
  19.  
  20.     /* Make sure there is a host name specified */
  21.  
  22.     if (host == NULL || *host == '\0') {
  23.  
  24.         errno = EDESTADDRREQ;
  25.         return(-1);
  26.     }
  27.  
  28.     /* Get the host file entry for the named host */
  29.  
  30.     if ((hentry = gethostbyname(host)) == NULL) {
  31.  
  32.         errno = ECONNREFUSED;
  33.         return(-1);
  34.     }
  35.  
  36.     /* Clear the socket structure */
  37.  
  38.     bzero((char *)&sa, sizeof(sa));
  39.  
  40.     /* Put the host's address in the socket structure */
  41.  
  42.     bcopy(hentry->h_addr, (char *)&sa.sin_addr, hentry->h_length);
  43.  
  44.     /* Set the address type and port */
  45.  
  46.     sa.sin_family = hentry->h_addrtype;
  47.     sa.sin_port = htons((unsigned short)port);
  48.  
  49.     /* Open the socket */
  50.  
  51.     if ((socket_fd = socket(hentry->h_addrtype, SOCK_STREAM, 0)) < 0)
  52.         return(-1);
  53.     
  54.     /* Connect to the port */
  55.  
  56.     if (connect(socket_fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)
  57.         return(-1);
  58.     
  59.     /* Return the socket descriptor */
  60.  
  61.     return(socket_fd);
  62. }
  63.